<template>
  <!-- 工单表表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="1200"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="50px">
      <el-row>
        <!--<el-col :span="8">
          <el-form-item label="产品" prop="materialCode">
            <el-input
              v-model="formData.materialCode"
              placeholder="请输入产品"
              clearable
              readonly
              @click="showWorkOrderSelect"
              style="width: 220px"
            >
              <template #append>
                <el-button @click="resetMaterial">清除</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>-->
        <el-col :span="5">
          <el-form-item label="日期" prop="planDate">
            <el-date-picker
              v-model="formData.planDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="">
            <el-button type="primary" @click="getPlanWorkingForm"
              >查询</el-button
            >
            <!--<el-button @click="resetForm">重置</el-button>-->
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!--<el-col :span="8">
          <el-form-item label="班制" prop="shiftSystemId">
            <el-select
              v-model="formData.shiftSystemId"
              placeholder="请选择班制"
              @change="changeShiftSet"
              style="width: 220px"
              clearable
            >
              <el-option
                v-for="item in shiftSetList"
                :key="item.id"
                :label="item.shiftSetName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="班次" prop="shiftId">
            <el-select
              v-model="formData.shiftId"
              placeholder="请输入班次"
              clearable
              style="width: 220px"
            >
              <el-option
                v-for="item in shiftList"
                :key="item.id"
                :label="item.shiftCode"
                :value="item.shiftId"
              />
            </el-select>
          </el-form-item>
        </el-col>-->
      </el-row>
      <el-card shadow="never" class="table-container">
        <div class="formTable2">
          <el-table
            :data="details"
            :key="Math.random"
            border
            style="width: 100%"
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />
            <el-table-column
              label="产品名称"
              props="materialName"
              min-width="150"
            >
              <template #default="{ row }">
                {{ row.materialName }}
              </template>
            </el-table-column>
            <el-table-column
              label="计划数量"
              prop="planQuantity"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="right"
            />
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="120"
            >
              <template #default="scope">
                <el-button
                  :disabled="scope.$index == 0"
                  type="primary"
                  link
                  @click.stop="moveUp(scope.$index)"
                >
                  上移
                </el-button>
                <el-button
                  :disabled="scope.$index == details.length - 1"
                  type="primary"
                  link
                  @click.stop="shiftDown(scope.$index)"
                >
                  下移
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="details.length > 1"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >保 存</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
    <conten-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :plantId="formData.plantId"
      :brekList="brekList"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESDAYPLANADJUSTORDER",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  // materialCode: [{ required: true, message: "请输入产品", trigger: "change" }],
  planDate: [{ required: true, message: "请选择日期", trigger: "change" }],
  // shiftId: [{ required: true, message: "请选择班次", trigger: "change" }],
  // shiftSystemId: [{ required: true, message: "请选择班制", trigger: "change" }],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  producePlanCode: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  workSequence: "",
  planNum: "",
  planDate: getCurrentDate(),
  planQuantity: "",
  planStatus: "",
  productionVersionNumber: "",
  externalCode: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        producePlanCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        materialId,
        materialCode,
        materialName,
        workSequence,
        planNum,
        planDate,
        planQuantity,
        planStatus,
        productionVersionNumber,
        externalCode,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        producePlanCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        materialId,
        materialCode,
        materialName,
        workSequence,
        planNum,
        planDate,
        planQuantity,
        planStatus,
        productionVersionNumber,
        externalCode,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.producePlanCode = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.workSequence = "";
  formData.planNum = "";
  formData.planDate = getCurrentDate();
  formData.planQuantity = "";
  formData.planStatus = "";
  formData.productionVersionNumber = "";
  formData.externalCode = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
  shiftList.value = [];
  details.value = [];
}
const classifyList = [
  {
    id: "0",
    name: "制芯",
  },
  {
    id: "1",
    name: "组芯",
  },
];
const changeClassify = (val) => {
  if (val === "0") {
    formData.classify = "0";
  }
};
const loading = ref(false);

/** 工单表保存提交 */
async function handleSubmit() {
  loading.value = true;
  details.value.forEach((item, index) => {
    item.workSequence = index + 1;
  });
  await request({
    url: "/mes/mesdayplan/saveBatch",
    method: "post",
    data: details.value,
  }).finally(() => {
    loading.value = false;
  });
  ElMessage.success(`保存成功`);
  closeDialog();
  emit("reset-table", formData.id);
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
onMounted(() => {
  getShiftSetList();
});
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};
//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    formData.materialId = data.id;
    formData.materialCode = data.materialCode;
  }
};
// 回显的数据
const brekList = ref([]);
const resetMaterial = () => {
  formData.materialId = "";
  formData.materialCode = "";
};

// 获取当前日期yyyymmdd
function getCurrentDate() {
  const today = new Date();
  let year = today.getFullYear();
  let month = (today.getMonth() + 1).toString().padStart(2, "0");
  let day = today.getDate().toString().padStart(2, "0");
  return year.toString() + "-" + month + "-" + day;
}
//班制
const shiftSetList = ref([]);
async function getShiftSetList() {
  await request({
    url: "mes/messhiftset/getList",
    method: "post",
    data: { plantId: formData.plantId, enabled: 1 },
  }).then((res) => {
    shiftSetList.value = res.data;
  });
}
function changeShiftSet(val) {
  formData.shiftSystemId = val;
  formData.shiftId = "";
  shiftList.value = [];
  if (val) {
    getShifts();
  }
}

//班次
const shiftList = ref([]);
async function getShifts() {
  await request({
    url: "mes/messhiftset/getDetails",
    method: "post",
    data: {
      id: formData.shiftSystemId,
    },
  }).then((res) => {
    shiftList.value = res.data;
  });
}
//获取查询条件下的工单列表
const details = ref([]);
async function getPlanWorkingForm() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      await request({
        url: "/mes/mesdayplan/getList",
        method: "post",
        data: formData,
      }).then((res: any) => {
        if (res.code == 200) {
          details.value = res.data;
        }
      });
    }
  });
}
const moveUp = (index: number) => {
  const temp = details.value[index];
  details.value.splice(index, 1);
  details.value.splice(index - 1, 0, temp);
};
const shiftDown = (index: number) => {
  const temp = details.value[index];
  details.value.splice(index, 1);
  details.value.splice(index + 1, 0, temp);
};
</script>
